package org.yun.util;


import org.yun.biz.model.Prize;
import org.yun.constants.Constant;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author liyunfeng31
 */
public class ArithmeticUtil {
    /**
     * 倍数
     */
    private static final int MULTIPLE = 100000000;

    private static final BigDecimal FACTOR = new BigDecimal(MULTIPLE);


    public static Map<String, Prize> doLottery(List<Prize> prizes){
        int lastScope = 0;
        Map<Prize, int[]> prizeScopes = new HashMap<>(prizes.size());
        Prize thanks = null;
        for (Prize prize : prizes) {
            if(prize.getPrizeType() == Constant.PRIZE_THANKS){ thanks = prize; }
            int currentScope = lastScope + prize.getRatio().multiply(FACTOR).intValue();
            prizeScopes.put(prize, new int[] { lastScope + 1, currentScope });
            lastScope = currentScope;
        }
        // 获取1-100000000之间的一个随机数
        int luckyNumber = ThreadLocalRandom.current().nextInt(MULTIPLE);
        // 查找随机数所在的区间
        Map<String, Prize> resultMap = new HashMap<>(2);
        resultMap.put(Constant.THANKS, thanks);

        Set<Map.Entry<Prize, int[]>> entrySets = prizeScopes.entrySet();
        for (Map.Entry<Prize, int[]> m : entrySets) {
            if (luckyNumber >= m.getValue()[0] && luckyNumber <= m.getValue()[1]) {
                resultMap.put(Constant.LUCK, m.getKey());
                return resultMap;
            }
        }
        return resultMap;
    }
}
